<?php
namespace app\know\controller;

use app\know\model\ChapterModel;
use app\know\controller\AdminKnowBaseController;
use app\know\validate\MaterialValidate;
use app\know\model\SysConfigModel;
use app\know\model\MaterialModel;

/**
 * Class AdminLearningMaterialController 资料管理控制器
 * @package app\know\controller
 */
class AdminLearningMaterialController extends AdminKnowBaseController
{
    /**
     * 资料管理
     * @adminMenu(
     *     'name'   => '资料管理',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 37000,
     *     'icon'   => '',
     *     'remark' => '资料管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_learning_material_index_view');

        if (!empty($content)) 
		{
            return $content;
        }
		
        return $this->fetch();
    }

    /**
     * 资料列表
     * @adminMenu(
     *     'name'   => '资料列表',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 37200,
     *     'icon'   => '',
     *     'remark' => '资料列表',
     *     'param'  => ''
     * )
     */
    public function learning()
    {
        $content = hook_one('know_admin_learning_material_learning_view');

        if (!empty($content)) 
		{
            return $content;
        }
		
		$ds = SysConfigModel::where([['type', 'in', ['SUBJECT', 'GRADE', 'TEXTBOOK_VERSION', 'TEXTBOOK_VOLUME']], ['is_delete', '=', 0]])->select();
		$subjects = [];
		$grades = [];
		$versions = [];
		$volumes = [];
		
		foreach($ds as $k => $v) 
		{
			if ($v['type'] == 'SUBJECT') 
			{
				array_push($subjects, $v);
			} 
			else if ($v['type'] == 'GRADE') 
			{
				array_push($grades, $v);
			} 
			else if ($v['type'] == 'TEXTBOOK_VERSION') 
			{
				array_push($versions, $v);
			} 
			else if ($v['type'] == 'TEXTBOOK_VOLUME') 
			{
				array_push($volumes, $v);
			}
		}
		
		$this->assign('subjects', $subjects);
		$this->assign('grades', $grades);
		$this->assign('versions', $versions);
		$this->assign('volumes', $volumes);
		
        return $this->fetch();
    }
	
    public function list()
    {
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');
        $subject_code = $this->request->param('subject_code', '');
        $grade_code = $this->request->param('grade_code', '');

        $where = ['is_delete' => 0, 'material_type' => 'learn'];
        if ($subject_code)
        {
            $where['subject_code'] = $subject_code;
        }
        if ($grade_code)
        {
            $where['grade_code'] = $grade_code;
        }

        $count = MaterialModel::where($where)->count();

        $rows = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->page($pageNumber, $pageSize)
                                    ->select();
									
        $ds = SysConfigModel::where([['type', 'in', ['SUBJECT', 'GRADE', 'TEXTBOOK_VERSION', 'TEXTBOOK_VOLUME']], ['is_delete', '=', 0]])->select();
		foreach($rows as $k => $v) 
		{
			foreach($ds as $k1 => $v1) 
			{
				if ($v['grade_code'] == $v1['key'] && $v1['type'] == 'GRADE') 
				{
					$v['grade'] = $v1['value'];
				} 
				else if ($v['subject_code'] == $v1['key'] && $v1['type'] == 'SUBJECT') 
				{
					$v['subject'] = $v1['value'];
				} 
				else if ($v['textbook_version_code'] == $v1['key'] && $v1['type'] == 'TEXTBOOK_VERSION') 
				{
					$v['version'] = $v1['value'];
				} 
				else if ($v['textbook_volume_code'] == $v1['key'] && $v1['type'] == 'TEXTBOOK_VOLUME') 
				{
					$v['volume'] = $v1['value'];
				}
			}
		}		
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];

        try 
		{
			$model = new MaterialModel();
			$param['uuid'] = $model->getUUID();
            $param['material_type'] = 'learn';
            $this->validateFailError($param, 'Material.add');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $row = MaterialModel::create($param);
        if ($row) 
		{
            $this->opLog([
                'table_name' => 'know_material',
                'sql' => MaterialModel::getLastSql(),
                'create_user' => $user['user_login'],
            ]);
            $this->success('添加成功');
        }
        $this->error('添加失败');  
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'Material.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
		{
            MaterialModel::where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => 'know_material',
                'sql' => MaterialModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'Material.edit');
        } 
		catch (ValidateException $e) 
		{
            $this->result('', 0, $e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        try 
		{
            $d = MaterialModel::find($id);
            MaterialModel::where('id', $id)->save($param);
            $this->opLog([
                'table_name' => 'know_material',
                'sql' => MaterialModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('修改成功');
    }

    public function maxOrder()
    {
        $order = MaterialModel::max('order_number');
        $this->success('', '', $order);
    }
}
